<template>
  <div class="app-container">

    <!--订单信息查询条件-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="销售号" prop="docNum">
          <el-input
            v-model="queryParams.docNum"
            placeholder="请输入销售号模糊查询"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 250px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="是否完成">
          <el-select v-model="queryParams.value" clearable  placeholder="请选择" style="width: 250px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户名称" prop="custName">
          <el-input
            v-model="queryParams.custName"
            placeholder="请输入客户名称模糊查询"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 250px"
            @blur="trimOnBlur"
          />
        </el-form-item>

        <el-form-item label="订单状态" prop="dicSysNormalDisable">
          <el-select
            v-model="queryParams.dicSysNormalDisable"
            placeholder="请选择订单状态"
            clearable
            style="width: 250px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="订单完成日期">
          <el-date-picker
            v-model="queryParams.dtRange"
            style="width: 250px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:crmOrders:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:crmOrders:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:crmOrders:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:crmOrders:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 订单信息列表-->
    <el-table v-loading="loading"
              stripe
              :data="crmOrdersList"
              :highlight-current-row="true"
              @selection-change="handleSelectionChange"
           >
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props" align="center">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="订单时间" align="center" prop="docDt" width="150"/>
      <el-table-column label="销售号" align="center" prop="docNum" width="150" />
      <el-table-column label="客户名称" align="center" prop="custName" width="180" />
      <el-table-column label="客户编号" align="center" prop="custNum" width="180"/>
      <el-table-column label="销售人员" align="center" prop="salesPerson" width="120"/>
      <el-table-column label="交付日期" align="center" prop="orderDeliveryDate" width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDeliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额(￥)" align="right" prop="orderAmt" width="120">
        <template slot-scope="scope">
          {{ numFormat_thousandsSeparator(fun(scope.row.orderAmt)) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="dicSysNormalDisable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.dicSysNormalDisable"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订单完成日期" align="center" prop="stockInDocDt" width="120" >
        <template slot-scope="scope">
          <span v-if="scope.row.stockInDocDt">{{ parseTime(scope.row.stockInDocDt, '{y}-{m}-{d}') }}</span>
          <el-tag type="info" size="mini" v-show="!scope.row.stockInDocDt">未完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" align="center" prop="itemName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="right" prop="orderDetailQty" width="120"/>
      <el-table-column label="单价(￥)" align="right" prop="orderDetailAmt" width="120">
        <template slot-scope="scope">
          {{ numFormat_thousandsSeparator(calculate(scope.row.orderDetailAmt)) }}
        </template>
      </el-table-column>
      <el-table-column label="含税单价" align="right" prop="unitPriceTaxIncluded" width="120"/>
      <el-table-column label="不含税金额" align="right" prop="orderDetailTotalAmt" width="150">
        <template slot-scope="scope">
          {{ numFormat_thousandsSeparator(calculate(scope.row.orderDetailTotalAmt)) }}
        </template>
      </el-table-column>
      <el-table-column label="税率(%)" align="right" prop="taxRate" width="120"/>
      <el-table-column label="税额" align="right" prop="taxAmt" width="150">
        <template slot-scope="scope">
          {{ numFormat_thousandsSeparator(calculate(scope.row.taxAmt)) }}
        </template>
      </el-table-column>
      <el-table-column label="价税合计" align="right" prop="totalPriceAndTax" width="150" >
        <template slot-scope="scope">
          {{ numFormat_thousandsSeparator(calculate(scope.row.totalPriceAndTax)) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:crmOrders:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:crmOrders:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">
            删除
          </el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['oa:confirm:edit']"
            :disabled="scope.row.oaDictConfirmStatus !='waiting'">
            审核
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!--分页查询-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                  style="margin-bottom: 15px;"
                  :title="form.latestTaskInfo"
                  type="info"
                  :closable="false"
                  effect="dark"
                  >
        </el-alert>

        <!--基本信息-->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>基本信息</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_form_order"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>
          <div v-show="fold_form_order== 'false'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="客户名称" prop="fkCustUuid">
                  <el-select
                    filterable
                    v-model="form.fkCustUuid"
                    placeholder="请选择客户名称"
                    clearable
                    :style="{width: '100%'}" >
                    <el-option
                      v-for="item in custNameOptions"
                      :key="item.custUuid"
                      :label="item.custName"
                      :value="item.custUuid"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="订单时间" prop="docDt">
                  <el-date-picker clearable
                                  v-model="form.docDt"
                                  type="datetime"
                                  format="yyyy-MM-dd HH:mm"
                                  value-format="yyyy-MM-dd HH:mm"
                                  placeholder="选择订单日期时间" :style="{width: '100%'}"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item prop="orderAmt">
                  <span slot="label">订单金额
                    <el-tooltip content="价税合计金额，该数值根据输入明细自动汇总" placement="top">
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>

                  <el-input v-model="form.orderAmt" :style="{width: '100%'}"
                            @blur="trimOnBlur" :disabled="true">
                    <template slot="append">（元）</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="销售人员" prop="fkAttentionUserId">
                  <el-input v-model="form.fkAttentionUserId" v-show="false"/>
                  <el-input placeholder="请选择销售员" readOnly="true" v-model="form.salesPerson"
                            class="input-with-select" :style="{width: '100%'}" >
                    <el-button @click="showDialog_selectSalePerson(form)" slot="append" icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>

              </el-col>
              <el-col :span="12">

                <el-form-item label="订单编号" prop="docNum">
                  <el-input v-model="form.docNum" placeholder="请输入订单编号"
                            :style="{width: '100%'}"  @blur="trimOnBlur"/>
                </el-form-item>

                <el-form-item label="交付日期" prop="orderDeliveryDate">
                  <el-date-picker clearable
                                  v-model="form.orderDeliveryDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择交付日期" :style="{width: '100%'}"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="订单状态" prop="dicSysNormalDisable">
                  <el-select v-model="form.dicSysNormalDisable" placeholder="请选择订单状态" :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>

              </el-col>

              <el-col :span="24">
                <el-form-item label="备注" prop="docNote">
                  <el-input v-model="form.docNote"
                            type="textarea"
                            autosize
                            placeholder="请输入内容"
                            :style="{width: '100%'}" @blur="trimOnBlur" maxlength="50"
                            show-word-limit/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <!--明细信息-->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>明细信息</b></span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="mini"
                         @click="handleAddCrmOrderDetails"
                         :disabled="form.oaDictConfirmStatus != 'editing'">添加
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="handleDeleteCrmOrderDetails"
                         :disabled="form.oaDictConfirmStatus != 'editing'">删除
              </el-button>
            </el-col>
          </el-row>
          <el-table :data="crmOrderDetailsList" :row-class-name="rowCrmOrderDetailsIndex"
                    @selection-change="handleCrmOrderDetailsSelectionChange" ref="crmOrderDetails">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" prop="orderDetailOrderBy" align="center" width="120px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderDetailOrderBy" placeholder="请输入序号"
                          @blur="trimOnBlur"/>
              </template>
            </el-table-column>
            <el-table-column label="物料名称" prop="itemName" width="240px" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderDetailItemUuid" v-show="false"/>
                <el-input placeholder="请选择物料名称" readOnly="true" v-model="scope.row.itemName"
                          class="input-with-select">
                  <el-button @click="dialog_show_selectItem(scope)" slot="append" icon="el-icon-search"
                             ></el-button>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="计量单位" prop="orderUnit" width="200px" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.orderUnit"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="dict in orderUnitOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="数量" prop="orderDetailQty" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderDetailQty" placeholder="请输入数量" @blur="trimOnBlur"
                          @input="inputChange(scope)"/>
              </template>

            </el-table-column>

            <el-table-column label="不含税单价" prop="orderDetailAmt" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderDetailAmt" placeholder="请输入单价"
                           @blur="trimOnBlur" v-show="false"/>
                <span>{{calculate(scope.row.orderDetailAmt)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="含税单价" prop="unitPriceTaxIncluded" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unitPriceTaxIncluded" placeholder="请输入含税单价"
                          @blur="trimOnBlur" @input="inputChange(scope)"/>
              </template>
            </el-table-column>

            <el-table-column label="不含税金额" prop="orderDetailTotalAmt" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderDetailTotalAmt" placeholder="请输入金额"
                         @blur="trimOnBlur" v-show="false"/>
                <span>{{calculate(scope.row.orderDetailTotalAmt)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="税率" prop="taxRate" width="150px" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.taxRate"
                  placeholder="请选择税率"
                  style="width: 150px"
                  @input="inputChange(scope)"
                >
                  <el-option
                    v-for="dict in taxRateOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="税额" prop="taxAmt" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.taxAmt" placeholder="请输入税额"
                          @blur="trimOnBlur" v-show="false"/>
                <span>{{calculate(scope.row.taxAmt)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="价税合计" prop="totalPriceAndTax" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.totalPriceAndTax" placeholder="请输入价税合计"
                          @blur="trimOnBlur" v-show="false"/>
                <span>{{calculate(scope.row.totalPriceAndTax)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="紧急程度" prop="dicMesUrgencyLevel" width="200px" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.dicMesUrgencyLevel"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="dict in urgencyOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="明细状态" prop="sysNormalDisable" width="200px" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.sysNormalDisable"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="docNote" align="center" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.docNote" placeholder="请输入备注"
                          @blur="trimOnBlur" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <select-user ref="component_selectSalePerson" @ok="selectSalePerson_done" />
    <select-item ref="component_selectItem" @ok="selectItem_done"/>
    <confirm ref="component_confirm" @ok="confirm_done"/>

  </div>
</template>
<script>
  import {listCrmOrders, getCrmOrders, delCrmOrders, addCrmOrders, updateCrmOrders, findCustName} from "@/api/crm/crmOrders";
  import {newDocNum} from "@/api/oa/docNum";
  import {numFormat_thousandsSeparator} from "@/utils/num";
  import selectItem from "../../wms/wmsItems/selectItem";
  import selectUser from "../../comn/userGroup/selectUser";
  import confirm from "../../oa/confirm";
  import { trimOnBlur } from '@/utils/form'
  import { parseTime } from '@/utils/ruoyi'
  export default {
    dicts: ['sys_normal_disable', 'crm_dict_urgency_level',
      'wms_dict_measuring_unit', 'oa_dict_confirm_status','crm_dict_tax_rate'],
    name: "CrmOrders",
    components: {selectItem, selectUser, confirm},
    data() {
      let validateStartTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error("订单时间不能为空"));
        } else {
          // 如果交付日期没选
          if (!this.form.orderDeliveryDate) {
            callback();
          } else {
            // 交付日期有进行判断
            if (this.compareDate(value, this.form.orderDeliveryDate)) {
              // 如果订单时间在交付日期之前
              callback();
            } else {
              callback(new Error("订单时间不能再交付日期之后，请重新选择"));
            }
          }
        }
      };
      let validateEndTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error("交付日期不能为空"));
        } else {
          if (!this.form.docDt) {
            callback();
          } else {
            // 订单时间有
            if (this.compareDate(this.form.docDt, value)) {
              callback();
            } else {
              callback(new Error("交付日期不能在订单时间前，请重新选择"));
            }
          }
        }
      };
      return {
        fold_form_order: 'false',
        // 遮罩层
        loading: true,
        readOnly:true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedCrmOrderDetails: [],
        //客户下拉框列表
        custNameOptions: [],
        //系统状态字典下拉
        statusOptions: [],
        //时间区间
        dateRange: [],
        //紧急程度下拉
        urgencyOptions: [],
        taxRateOptions: [],
        //物料下拉列表
        itemNameOptions: [],
        //计量单位下拉
        orderUnitOptions: [],
        //销售人员下拉列表
        salesList: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单信息表格数据
        crmOrdersList: [],
        // 订单明细表格数据
        crmOrderDetailsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层
        open_report: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          docNum: null,
          orderTitle: null,
          orderDate: null,
          orderDeliveryDate: null,
          orderAmt: null,
          fkCustUuid: null,
          dicSysNormalDisable: null,
          dictMesUrgencyLevel: null,
          orderNote: null,
          userId: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          fkCustUuid: [
            {required: true, message: '请选择客户名称', trigger: 'change'}
          ],
          docNum: [
            {required: true, message: '请输入订单编号', trigger: 'change'}
          ],
          orderAmt: [
            {required: true, message: '请填写明细信息', trigger: 'change'}
          ],
          dicSysNormalDisable: [
            {required: true, message: '请选择订单状态', trigger: 'change'}
          ],
          fkAttentionUserId:[
            {required: true, message: '请选择销售人员', trigger: 'change'}
          ],
          docDt: [
            {
              trigger: ["change"],
              validator: validateStartTime,
            },
          ],
          orderDeliveryDate: [
            {
              trigger: ["change"],
              validator: validateEndTime,
            },
          ],
        },
        orderDetails_currRowScope: null, // 订单明细：当前行
        // 列信息
        columns: [
          {key: 0, label: `订单编号`, visible: true},
          {key: 1, label: `客户名称`, visible: true},
          {key: 2, label: `客户编号`, visible: true},
          {key: 3, label: `销售人员`, visible: true},
          {key: 4, label: `订单日期`, visible: true},
          {key: 5, label: `交付日期`, visible: true},
          {key: 6, label: `金额(￥)`, visible: true},
          {key: 7, label: `订单状态`, visible: true},
          {key: 8, label: `审核状态`, visible: true},
          {key: 9, label: `订单完成日期`, visible: true},
          {key: 10, label: `单价`, visible: true},
          {key: 11, label: `数量`, visible: true},
          {key: 12, label: `金额`, visible: true}
        ],
        options: [{
          value:1,
          label: '已完成'
        }, {
          value:2,
          label: '未完成'
        }
        ]
      };

    },
    created() {

      // $route params
      let orderDocNum = this.$route.params && this.$route.params.orderDocNum;
      if (orderDocNum) {
        this.queryParams.docNum = orderDocNum
      }else console.log('！！！ 无参数 ！！！')


      this.getList();
      this.getList_key();
      /**获取系统开关字典数据*/
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      /**获取紧急程度字典数据*/
      this.getDicts("crm_dict_urgency_level").then(response => {
        this.urgencyOptions = response.data;
      });
      /**获取计量单位字典数据*/
      this.getDicts("wms_dict_measuring_unit").then(response => {
        this.orderUnitOptions = response.data;
      });
      /**获取税率字典数据*/
      this.getDicts("crm_dict_tax_rate").then(response => {
        this.taxRateOptions = response.data;
      });
    },

    methods: {
      // 比较两个日期
      compareDate(start, end) {
        return new Date(end).getTime() >= new Date(start).getTime();
      },
      trimOnBlur,
      inputChange(scope){
        //价税合计
        scope.row.totalPriceAndTax = scope.row.orderDetailQty*scope.row.unitPriceTaxIncluded
        //表头订单金额求和
        let sum = 0;
        this.crmOrderDetailsList.forEach((item) => {
          //遍历totalPriceAndTax这个字段，并累加
          sum += parseFloat(item.totalPriceAndTax);
        });
        //返回
        this.form.orderAmt = sum;
        //不含税金额
        scope.row.orderDetailTotalAmt = parseFloat(scope.row.totalPriceAndTax)/(1+parseFloat(scope.row.taxRate)/100)
        //税额
        scope.row.taxAmt = scope.row.orderDetailTotalAmt*scope.row.taxRate/100
        //不含税单价
        scope.row.orderDetailAmt = scope.row.orderDetailTotalAmt/scope.row.orderDetailQty
      },
      //保留两位小数
      fun(val) {
        return Number(val).toFixed(2);
      },
      //保留六位小数
      calculate(val) {
        return Number(val).toFixed(6);
      },
      numFormat_thousandsSeparator,
      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'crm_orders',
          uuidColumn: 'order_uuid',
          fkUuid: row.orderUuid,
          attentionUserNickName: row.salesPerson,
          oaDictConfirmStatus: row.oaDictConfirmStatus,
          msg: `请审核订单管理, 单据编号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);
      },


      getList() {

        this.loading = true;
        if( this.queryParams.dtRange ){
          this.queryParams.dtRangeBegin = this.queryParams.dtRange[0]
          this.queryParams.dtRangeEnd = this.queryParams.dtRange[1]
        }else {
          this.queryParams.dtRangeBegin = null
          this.queryParams.dtRangeEnd = null
        }
        /** 查询订单信息列表 */
        listCrmOrders(this.queryParams).then(response => {
          console.log(response)
          this.crmOrdersList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        /** 获取客户名称数据 */
        findCustName().then(response => {
          console.log(response)
          this.custNameOptions = response.rows
        });
      },

      getList_key() {
        this.getConfigKey("editing_confirm").then(response => {
          console.log(response)
          this.edit = response.msg;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          orderUuid: null,
          orderNum: null,
          docNum: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          orderTitle: null,
          orderDate: null,
          orderDeliveryDate: null,
          orderAmt: null,
          fkCustUuid: null,
          nickName:null,
          attentionUserName: null,
          dicSysNormalDisable: '0',
          oaDictConfirmStatus: null,
          fkAttentionUserId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          dictMesUrgencyLevel: null,
          orderNote: null,
          userId: null
        };
        this.crmOrderDetailsList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.orderDetailUuid)
        this.docs = selection.map(item => item.docNum)
        this.custs = selection.map(item => item.custName)
        this.single = selection.length !== 1
        this.oaDictConfirmStatus = selection.map(i=>i.oaDictConfirmStatus)
        let editing = 'editing';
        this.multiple=
          (this.oaDictConfirmStatus.indexOf(editing)>-1 && [...new Set(this.oaDictConfirmStatus)]==editing) ? false : true
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        newDocNum({preCode:'ORD-', len: 12}).then(response => {
          this.form.docNum = response.msg
        })

        this.form.oaDictConfirmStatus = 'editing'
        this.open = true;
        this.title = "添加订单信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderUuid = row.orderUuid || this.ids
        console.log(orderUuid)
        getCrmOrders(orderUuid).then(response => {
          this.form = response.data;
          this.crmOrderDetailsList = response.data.crmOrderDetailsList;
          console.log(this.form)
          // 审核
          this.form.oaDictConfirmStatus =
            ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
              ? 'editing' : this.form.oaDictConfirmStatus

          if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
            this.form.latestTaskInfo='💡 该条记录审核状态为'+
              this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
          }
          console.log(this.crmOrderDetailsList)
          this.open = true;
          this.title = "修改订单信息";
        });
      },

      /** 提交按钮 */
      submitForm(confirmStatus) {
        // 提交待审

        console.log(this.form.oaDictConfirmStatus)
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            this.form.crmOrderDetailsList = this.crmOrderDetailsList;
            if (this.form.orderUuid != null) {
              updateCrmOrders(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCrmOrders(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // submit_confirm() {
      //   this.form.oaDictConfirmStatus = 'waiting'
      //   submitConfirm(this.form).then(response => {
      //     this.$modal.msgSuccess("提交待审成功");
      //     this.open = false;
      //     this.getList();
      //   });
      // },

      /** 删除按钮操作 */
      handleDelete(row) {
        const orderDetailUuids = row.orderDetailUuid || this.ids;
        const docNums = row.docNum || this.docs;
        const custNames = row.custName || this.custs;
        console.log(orderDetailUuids)
        this.$modal.confirm('是否确认删除销售号为"' +docNums + '",' +
          '客户名称为"' + custNames + '"的订单？', '删除确认').then(function () {
          return delCrmOrders(orderDetailUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 订单明细序号 */
      rowCrmOrderDetailsIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },

      /** 订单明细添加按钮操作 */
      handleAddCrmOrderDetails() {
        let obj = {};
        obj.orderDetailOrderBy = "1";
        obj.orderDetailItemUuid = "";
        obj.itemName = "";
        obj.itemNum = "";
        obj.orderDetailAmt = "0";
        obj.orderDetailQty = "1";
        obj.orderDetailTotalAmt = "0";
        obj.orderDetailDescJson = "";
        obj.dicMesUrgencyLevel = "1";
        obj.sysNormalDisable = "0";
        obj.docNote = "";
        obj.orderUnit = "";
        obj.taxAmt = "0";
        obj.taxRate = "0";
        obj.unitPriceTaxIncluded = "0";
        obj.wmsDictMeasuringUnit = "";
        obj.totalPriceAndTax = "0";
        this.crmOrderDetailsList.push(obj);
      },

      /** 订单明细删除按钮操作 */
      handleDeleteCrmOrderDetails() {
        if (this.checkedCrmOrderDetails.length == 0) {
          this.$modal.msgError("请先选择要删除的订单明细数据");
        } else {
          const crmOrderDetailsList = this.crmOrderDetailsList;
          const checkedCrmOrderDetails = this.checkedCrmOrderDetails;
          this.crmOrderDetailsList = crmOrderDetailsList.filter(function (item) {
            return checkedCrmOrderDetails.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleCrmOrderDetailsSelectionChange(selection) {
        this.checkedCrmOrderDetails = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('crm/crmOrders/export', {
          ...this.queryParams
        }, `crm_crmOrders.xlsx`)
      },
      // /** 打开授权用户表弹窗 */
      // dialog_show_selectSalesPerson() {
      //   this.$refs.component_selectSalesPerson.show();
      // },

      /** 显示对话框：选择物料 */
      dialog_show_selectItem(scope) {
        console.log(scope)
        this.orderDetails_currRowScope = scope
        this.$refs.component_selectItem.dialog_show_selectItem();
      },


      // /** 选择用户完成 */
      // selectSalesPerson_done(user) {
      //   console.log(user)
      //   this.form.fkAttentionUserId = user.fkUserId
      //   this.form.salesPerson = `${user.nickName}（用户名：${user.nickName}，ID：${user.fkUserId}）`
      // },

      // 完成：选择物料
      selectItem_done(item) {
        console.log(item)
        this.orderDetails_currRowScope.row.itemName = item.itemName
        this.orderDetails_currRowScope.row.orderDetailItemUuid = item.itemUuid
        this.orderDetails_currRowScope.row.orderUnit = item.wmsDictMeasuringUnit

      },
      confirm_done() {
        this.getList()
      },
      /** 选择经办人 */
      showDialog_selectSalePerson( form ) {
        this.currentForm = form
        this.$refs.component_selectSalePerson.userGroup = 'salespeople';
        this.$refs.component_selectSalePerson.show();
      },
      /** 选择经办人 - 完成 */
      selectSalePerson_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.salesPerson = user.userNickNameAndId
      },
    },
  };
</script>
